package com.itheima.service.impl;


import com.itheima.dao.AccountDao;
import com.itheima.service.AccountService;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class AccountServiceImpl implements AccountService {


    private DataSource dataSource;
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public void transfer(String outName, String inName, Double money) {
        // 创建事务管理器对象
        DataSourceTransactionManager dtm = new DataSourceTransactionManager();
        //为事务添加数据源
        dtm.setDataSource(dataSource);
        //创建事务定义对象
        TransactionDefinition td =  new DefaultTransactionDefinition();
        //创建事务状态对象,用于控制事务执行
        TransactionStatus ts =  dtm.getTransaction(td);
        accountDao.inMoney(outName,money);
        int i = 1/0;
        accountDao.outMoney(inName,money);

        //提交事务
        dtm.commit(ts);
    }

}
